package cdu.sl.aichatdemo.controller;

import cdu.sl.aichatdemo.pojo.dto.ApiResponse;
import cdu.sl.aichatdemo.pojo.dto.ChatHistoryDto;
import cdu.sl.aichatdemo.pojo.entity.CustomChatMemory;
import cdu.sl.aichatdemo.service.ChatClientService;
import cdu.sl.aichatdemo.service.TitleGenerateService;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;

/**
 * @Description
 * @Author sunlin5@asiainfo.com
 * @Date 2025/8/27
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/chat-client")
public class ChatClientController {
    private static final String DEFAULT_PROMPT = "你是一个博学的智能聊天助手，请根据用户提问回答！";

    private final ChatClient dashScopeChatClient;
    private final ChatClientService chatClientService;

    @Autowired
    private TitleGenerateService titleGenerateService;

    public ChatClientController(ChatMemory chatMemory, ChatClient.Builder chatClientBuilder, ChatClientService chatClientService) {
        this.chatClientService = chatClientService;


        this.dashScopeChatClient = chatClientBuilder
                .defaultSystem(DEFAULT_PROMPT)
                // 实现 Logger 的 Advisor
                .defaultAdvisors(
                        new SimpleLoggerAdvisor()
                )
                // 设置上下文记忆功能，使用自定义的ChatMemory
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
                // 设置 ChatClient 中 ChatModel 的 Options 参数
                .defaultOptions(
                        DashScopeChatOptions.builder()
                                .withTopP(0.7)
                                .build()
                )
                .build();
    }

    /**
     * ChatClient 简单调用
     */
    @GetMapping("/simple/chat")
    public String simpleChat(@RequestParam(value = "query", defaultValue = "你好，很高兴认识你，能简单介绍一下自己吗？") String query,
                             @RequestParam(value = "chat-id", defaultValue = "1") String chatId) {

        log.info("chat-id:{}", chatId);
        log.info("query:{}", query);
        return dashScopeChatClient.prompt(query)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                .call().content();

    }


    @GetMapping("/title")
    public String generateTitle(String conversationId) {
        return titleGenerateService.generateTitle(conversationId);
    }


    /**
     * ChatClient 流式调用
     */
    @GetMapping("/stream/chat")
    public Flux<String> streamChat(@RequestParam(value = "query", defaultValue = "你好，很高兴认识你，能简单介绍一下自己吗？") String query, String chatId, HttpServletResponse response) {
        log.info("流式调用 ，query:{},chatId:{}", query, chatId);
        response.setCharacterEncoding("UTF-8");
        return dashScopeChatClient.prompt(query)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId)).stream().content();
    }


    @GetMapping("/custom/chat")
    public Flux<String> customChat(@RequestParam("query") String query,
                                   @RequestParam("chatId") String chatId) {
        log.info("自定义聊天API，query: {}, chatId: {}", query, chatId);
        return dashScopeChatClient.prompt(query)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream().content();
    }

    /**
     * 测试自定义聊天记忆功能（非流式）
     */
    @GetMapping("/test/memory")
    public ApiResponse<String> testChatMemory(@RequestParam("query") String query,
                                              @RequestParam("chatId") String chatId) {
        try {
            log.info("测试聊天记忆API，query: {}, chatId: {}", query, chatId);
            String response = dashScopeChatClient.prompt(query)
                    .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                    .call().content();
            return ApiResponse.success("对话成功", response);
        } catch (Exception e) {
            log.error("对话失败", e);
            return ApiResponse.error("对话失败: " + e.getMessage());
        }
    }

    /**
     * 根据对话ID查询单次对话记录
     */
    @GetMapping("/records")
    public ApiResponse<List<CustomChatMemory>> getChatRecords(@RequestParam("conversationId") String conversationId) {
        try {
            log.info("查询对话记录API，conversationId: {}", conversationId);
            List<CustomChatMemory> records = chatClientService.getChatRecordsByConversationId(conversationId);
            return ApiResponse.success("查询对话记录成功", records);
        } catch (Exception e) {
            log.error("查询对话记录失败", e);
            return ApiResponse.error("查询对话记录失败: " + e.getMessage());
        }
    }

    /**
     * 根据用户ID查询历史对话记录（简化版）
     */
    @GetMapping("/history")
    public ApiResponse<List<ChatHistoryDto>> getChatHistory(@RequestParam(value = "userId", defaultValue = "1") Long userId) {
        try {
            log.info("查询用户历史对话API，userId: {}", userId);
            List<ChatHistoryDto> history = chatClientService.getChatHistoryDtoByUserId(userId);
            return ApiResponse.success("查询历史对话成功", history);
        } catch (Exception e) {
            log.error("查询历史对话失败", e);
            return ApiResponse.error("查询历史对话失败: " + e.getMessage());
        }
    }

    /**
     * 根据用户ID查询历史对话记录（原始数据）
     */
    @GetMapping("/history/raw")
    public ApiResponse<List<CustomChatMemory>> getChatHistoryRaw(@RequestParam(value = "userId", defaultValue = "1") Long userId) {
        try {
            log.info("查询用户历史对话原始数据API，userId: {}", userId);
            List<CustomChatMemory> history = chatClientService.getChatHistoryByUserId(userId);
            return ApiResponse.success("查询历史对话原始数据成功", history);
        } catch (Exception e) {
            log.error("查询历史对话原始数据失败", e);
            return ApiResponse.error("查询历史对话原始数据失败: " + e.getMessage());
        }
    }

    /**
     * 根据用户ID和对话ID查询具体对话内容
     */
    @GetMapping("/details")
    public ApiResponse<List<CustomChatMemory>> getChatDetails(@RequestParam(value = "userId", defaultValue = "1") Long userId,
                                                              @RequestParam("conversationId") String conversationId) {
        try {
            log.info("查询具体对话内容API，userId: {}, conversationId: {}", userId, conversationId);
            List<CustomChatMemory> details = chatClientService.getChatDetailsByUserIdAndConversationId(userId, conversationId);
            return ApiResponse.success("查询对话详情成功", details);
        } catch (Exception e) {
            log.error("查询对话详情失败", e);
            return ApiResponse.error("查询对话详情失败: " + e.getMessage());
        }
    }

}
